package com.nononsenseapps.feeder.ui.rule

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import cn.ekuma.odbo.mobile.ui.AbstractEditorRecordHolder
import cn.ekuma.odbo.mobile.ui.adapter.SampleEntityAdapter
import cn.ekuma.odbo.mobile.ui.adapter.SampleMapEntityAdapter
import com.nononsenseapps.feeder.db.entity.FEED_ITEM_RULE_ACTION
import com.nononsenseapps.feeder.db.entity.Feed
import com.nononsenseapps.feeder.db.entity.FeedRule
import com.nononsenseapps.feeder.ui.R
import com.nononsenseapps.feeder.util.FeedExtensions.feedRuleActionDictionary
import com.nononsenseapps.feeder.util.FeedExtensions.feedRuleSourceDictionary
import com.nononsenseapps.feeder.util.FeedExtensions.systemFeedDictionary
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.*

class FeedRuleEditorHolder(val coroutineScope: CoroutineScope, val context: Context, val listFeed: ()->List<Feed>): AbstractEditorRecordHolder<FeedRule>() {

    private lateinit var feedSelected: Spinner
    private lateinit var feedRuleTitle: EditText
    private lateinit var feedRuleDeleteRule: CheckBox

    private lateinit var feedRuleAble: CheckBox
    private lateinit var feedRuleContent: EditText

    private lateinit var feedRuleAction : Spinner
    private lateinit var feedRuleSource : Spinner

    private lateinit var feedRuleActionMoveFeed : Spinner
    private lateinit var feedRuleReplaceContent: EditText

    private lateinit var feedRuleReplaceContentLayout :View
    private lateinit var feedRuleActionMoveFeedLayout :View

    private lateinit var feedRuleValueRegexPattern : CheckBox

    val feedAdapter by lazy {
        object : SampleEntityAdapter<Feed>(context, allAble = true) {
            override fun displayItemToTextView(textView: TextView, item: Feed?, postion: Int) {
               item?.let { textView.text = item.displayTitle }
            }

            override fun displaySystemToView(textView: TextView, position: Int) {
                textView.text = context.getString(R.string.all_feeds)
            }
        }
    }

    override fun createValue(): FeedRule {
        val current=currentItem?:createNewItem(null)
        current.feedId=null
        feedSelected.selectedItem?.let {
            it as Feed
            current.feedId=it.id
        }
        current.title=feedRuleTitle.text.toString()
        current.adClick=feedRuleDeleteRule.isChecked
        current.able = feedRuleAble.isChecked

        val mapEnt=feedRuleSource.selectedItem as Pair<*, *>
        current.style= mapEnt.first as Int

        val temp = feedRuleAction.selectedItem as  Pair<*, *>
        current.actionType = temp.first as Int

        val ruleFeedRule = feedRuleActionMoveFeed.selectedItem
        if(ruleFeedRule != null) {
            ruleFeedRule as Pair<*, *>
            current.actionFeedId = ruleFeedRule.first as Long
        }

        current.ruleValue=feedRuleContent.text.toString()
        current.replaceValue= feedRuleReplaceContent.text.toString()
        current.regexPattern = feedRuleValueRegexPattern.isChecked

        return current
    }


    override fun refresh(item: FeedRule?){
        var feedIndex=-1
        val current=item?:createNewItem(null)
        current.feedId?.let{
            feedIndex=feedAdapter.getPosition(Feed(id = it))
        }
        feedSelected.setSelection(feedIndex)
        feedRuleTitle.setText(current.title)
        feedRuleContent.setText(current.ruleValue)
        feedRuleDeleteRule.isChecked= current.adClick
        feedRuleAble.isChecked=current.able
        feedRuleValueRegexPattern.isChecked=current.regexPattern

        editAble().let{
            feedSelected.isClickable=it
            feedRuleTitle.isEnabled=it
            feedRuleAble.isEnabled=it
            feedRuleContent.isEnabled=it
            feedRuleValueRegexPattern.isEnabled=it

            if(current.adClick){
                feedRuleAction.isEnabled=false
                feedRuleSource.isEnabled=false
                feedRuleActionMoveFeed.isEnabled=false
                feedRuleReplaceContent.isEnabled=false
            }else{
                feedRuleAction.isEnabled=it
                feedRuleSource.isEnabled=it
                feedRuleActionMoveFeed.isEnabled=it
                feedRuleReplaceContent.isEnabled=it

            }
        }

        feedRuleAction.setSelection(feedRuleActionDictionary.keys.indexOf(current.actionType))
        feedRuleSource.setSelection(feedRuleSourceDictionary.keys.indexOf(current.style))
        feedRuleActionMoveFeed.setSelection(systemFeedDictionary.keys.indexOf(current.actionFeedId))

        feedRuleReplaceContent.setText(current.replaceValue)

        updateUiVisibleCheck()
    }

    override fun getEditorViewPanel(inflater: LayoutInflater, container: ViewGroup): View {
        val  editorView=inflater.inflate(R.layout.edit_feed_rule, container,false)
        feedSelected=editorView.findViewById(R.id.feed_selected)
        feedSelected.onItemSelectedListener=object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {
                setDirty(true)
            }
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                setDirty(true)
            }
        }
        feedRuleTitle=editorView.findViewById(R.id.feed_rule_title)
        feedRuleTitle.setOnEditorActionListener { v, actionId, event ->
            setDirty(true)
            true
        }
        feedRuleDeleteRule=editorView.findViewById(R.id.feed_rule_ad_rule)
        feedRuleDeleteRule.isEnabled=false

        feedRuleContent=editorView.findViewById(R.id.feed_rule_content)

        feedSelected.adapter = feedAdapter

        feedRuleAble=editorView.findViewById(R.id.feed_rule_able)

        feedRuleAction=editorView.findViewById(R.id.feed_rule_action)

        feedRuleAction.adapter= object:SampleMapEntityAdapter<Int,Int>(context,feedRuleActionDictionary){
            override fun toString(itemValue: Int): String {
                return context.getString(itemValue)
            }
        }

        feedRuleAction.onItemSelectedListener=object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                setDirty(true)
                updateUiVisibleCheck()
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
                setDirty(true)
                updateUiVisibleCheck()
            }
        }

        feedRuleSource=editorView.findViewById(R.id.feed_rule_source)
        feedRuleSource.adapter = object:SampleMapEntityAdapter<Int,Int>(context,feedRuleSourceDictionary){
            override fun toString(itemValue: Int): String {
                return context.getString(itemValue)
            }
        }
        feedRuleSource.onItemSelectedListener=object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                setDirty(true)
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
                setDirty(true)
            }
        }


        feedRuleActionMoveFeed=editorView.findViewById(R.id.feed_rule_action_move_feed)
        feedRuleActionMoveFeed.adapter = object:SampleMapEntityAdapter<Long,Int>(context,systemFeedDictionary){
            override fun toString(itemValue: Int): String {
                return context.getString(itemValue)
            }
        }
        feedRuleActionMoveFeed.onItemSelectedListener=object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                setDirty(true)
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
                setDirty(true)
            }
        }

        feedRuleReplaceContent = editorView.findViewById(R.id.feed_rule_replace_content)

        feedRuleReplaceContentLayout = editorView.findViewById(R.id.feed_rule_replace_content_layout)

        feedRuleActionMoveFeedLayout = editorView.findViewById(R.id.feed_rule_action_move_feed_layout)

        feedRuleValueRegexPattern = editorView.findViewById(R.id.feed_rule_value_regex_pattern)

        coroutineScope.launch(Dispatchers.IO) {
            val  feedList=listFeed()
            withContext(Dispatchers.Main) {
                feedAdapter.addAll(feedList)
                refresh()
            }
        }

        return editorView
    }

    private fun updateUiVisibleCheck() {
        val temp = feedRuleAction.selectedItem as  Pair<*, *>

        when(temp.first as Int){
            FEED_ITEM_RULE_ACTION.MOVE_FEED ->{
                feedRuleReplaceContentLayout.visibility=View.GONE
                feedRuleActionMoveFeedLayout.visibility=View.VISIBLE
            }
            FEED_ITEM_RULE_ACTION.REPLACE -> {
                feedRuleReplaceContentLayout.visibility=View.VISIBLE
                feedRuleActionMoveFeedLayout.visibility=View.GONE
            }
           else -> {
               feedRuleReplaceContentLayout.visibility=View.GONE
               feedRuleActionMoveFeedLayout.visibility=View.GONE
           }
        }
    }

    override fun createNewItem(prop: Properties?): FeedRule {
        val item= FeedRule()
        return item
    }
}